import axios, { AxiosResponse } from "axios";
import { HuaweiTokenResponse, HuaweiUserInfo, tokenInfoRequest } from "../routes/auth";
import jwt from "jsonwebtoken";
import { AppDataSource } from "../config/database";
import { Role, User } from "../entities/User";
import { Unauthorized } from "http-errors";

class AuthService {
  // 获取用户凭证
  async getToken(code: string): Promise<HuaweiTokenResponse> {
    const tokenUrl = process.env.HUAWEI_TOKEN_URL;
    const clientId = process.env.HUAWEI_CLIENT_ID;
    const clientSecret = process.env.HUAWEI_CLIENT_SECRET;

    // 构造请求参数params
    const params = new URLSearchParams();
    params.append('grant_type', 'authorization_code');
    params.append('code', code);
    params.append('client_id', clientId);
    params.append('client_secret', clientSecret);

    const config = {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    };

    const res: AxiosResponse<HuaweiTokenResponse> = await axios.post(tokenUrl, params, config);
    return res.data;
  }

  // 获取用户信息
  async getUserInfo(tokenInfo: tokenInfoRequest): Promise<HuaweiUserInfo> {
    // 通过AccessToken获取用户相关信息
    const tokenInfoUrl = process.env.HUAWEI_TOKEN_INFO_URL
    const accessToken = tokenInfo.access_token;

    // 构造请求参数params
    const params = new URLSearchParams();
    params.append('access_token', accessToken);
    const res: AxiosResponse<HuaweiUserInfo> = await axios.post(tokenInfoUrl, params);
    return res.data;
  }

  // 生成token
  generateToken(id: string) {
    const payload: object = { id } // 存入id，方便登录验证
    return jwt.sign(payload, process.env.JWT_SECRET_KEY, { expiresIn: '30d' })
  }

  // 根据手机号查找用户
  async getUserByPhoneNumber(phoneNumber: string) {
    const userRepository = AppDataSource.getRepository(User);
    let user = await userRepository.findOneBy({ phoneNumber });

    if (!user) {
      user = userRepository.create({
        username: `用户${Date.now()}`,
        phoneNumber,
        role: Role.USER
      })
      await userRepository.save(user)
    }

    return user
  }

  // 根据unionId查找用户
  async getUserByUnionId(userInfo: HuaweiUserInfo) {
    const unionId = userInfo.unionID; // unionId
    const phoneNumber = userInfo.loginMobileNumber; // 明文手机号
    if (!unionId || !phoneNumber) throw new Unauthorized('获取用户身份信息失败');

    const userRepository = AppDataSource.getRepository(User);
    // 根据unionId查找用户
    let user = await userRepository.findOneBy({ unionId });
    if (!user) {
      // 看看能不能根据手机号查找到用户，找到了就合并账号
      user = await userRepository.findOneBy({ phoneNumber });
      if (user) {
        // 说明原先用户是手机号登录，然后退出登录后用华为账号登录
        // 需要兼容两种登录方式的账号
        user.unionId = unionId
      } else {
        // 用户不存在，创建新用户
        user = userRepository.create({
          unionId,
          username: `用户${Date.now()}`,
          phoneNumber,
          role: Role.USER
        })
      }
    }

    await userRepository.save(user)

    return user
  }
}

export const authService = new AuthService();